<template>
  <div style="position:relative">
    <!-- 营收列表 -->
    <div>
      <div style="display: flex;justify-content: center;">

        <div style="font-size: 20px;font-weight:700;color:#3a71a8;text-align: center;margin-bottom:10px">
          {{ luser.companyName }}应收应支统计表</div>
        <el-button size="small" @click="ex_getWalletListForBack_btn" style="margin-left: 20px;"
          type="warning">导出</el-button>
      </div>
      <div class="time-wrapper">

        <div>
          <el-select size="small" clearable style="width:100px;" v-model="find_data.cusTypeId" placeholder="客户类型">
            <el-option v-for="item in findCusTypeCombo_list" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
          <el-select size="small" filterable remote @change="handleFilter_change" :filter-method="handleFilter"
            clearable style="width:100px;margin-left: 5px;" v-model="find_data.userId" placeholder="客户">
            <el-option v-for="(item, index) in serviceCenterfindComboCusList_list" :key="item.userId"
              :label="item.cusCompanySimpleName" :value="item.userId">
              <span style="float: left">{{ item.cusCompanyName }}</span>
              <span style="
        float: right;
        color: var(--el-text-color-secondary);
        font-size: 13px;
      ">{{ item.cusRealName + '【' + item.cusPhone + '】' }}</span>
            </el-option>
          </el-select>

          <el-select size="small" style="width:100px;margin-left: 5px;" v-model="find_data.serviceMan" clearable
            placeholder="业务员">
            <el-option v-for="item in getServiceMans_list" :key="item.ftUserId" :label="item.realName"
              :value="item.ftUserId">
              <span style="float: left">{{ item.realName }}</span>
              <span style="
              float: right;
              color: var(--el-text-color-secondary);
              font-size: 13px;
            ">{{ item.loginPhone }}</span>
            </el-option>
          </el-select>


          <el-date-picker size="small" :default-time="defaultTime" style="margin-left: 5px;width: 200px;"
            v-model="timeTypeTime" @change="timeTypeTime_btn" type="daterange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />



          <el-button style="margin-left: 5px;" size="small" type="primary" @click="list_api()">搜索</el-button>
        </div>

      </div>
      <div style="display: flex;">
        <el-tag type="success">总应收:{{ totalGath }}元</el-tag>
        <el-divider direction="vertical"></el-divider>
        <el-tag type="danger">总应支:{{ totalPay }}元</el-tag>
      </div>
      <div class="empty-car-list" style="margin-top: 5px;">
        <div>
          <div>
            <el-table :scrollbar-always-on="true" :resizable='true' @header-dragend='headerdragend' border
              height="53.5vh" ref="multipleTableRef" :data="list_data"
              style="width: 100%;font-size: 12px; color: black;">
              <el-table-column label="编号" width="49" fixed type="index" />
              <template v-for="item in table_data_list_new" :key="item.field">
                <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                  <template v-if="item.field == 'serviceName'" #="{ row, column, $index }">
                    <span>{{ row.serviceName ? row.serviceName.split('-')[1] + '-' +
                      row.serviceName.split('-')[2] : '' }}</span>

                  </template>
                  <template v-if="item.field == 'dutyName'" #="{ row, column, $index }">

                    <el-tooltip :popper-class="'route-tips'" placement="left">
                        <template #content>{{ row.dutyName }}</template>
                        <span style="  width: 124px; white-space: nowrap; text-overflow: ellipsis; ">{{
                            row.dutyName }}</span>
                    </el-tooltip>

                </template>


                </el-table-column>
              </template>
            </el-table>
          </div>

          <!-- <div style="margin-top:20px">
            <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
              v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
              :page-sizes="[20, 50, 100, 200]" :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
              :total="total" />
          </div> -->
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <div>
      <!-- 表格筛选 -->
      <div v-show="false" style="position: absolute;top:62px;z-index: 2;"
        :style="icon_off ? 'right:-40px;' : 'right:70px;'">
        <el-icon @click="icon_btn" :size="20">
          <Setting />
        </el-icon>
        <div v-show="icon_off" style=" position: relative;top:-50px;right:160px;width: 150px;height:430px;background:#fff;overflow: hidden;border: 1px solid #c1afaf;
    border-radius: 4px; ">
          <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
            <div>
              <el-button-group style="display: flex; ">
                <el-tooltip effect="dark" placement="bottom">
                  <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                  <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                </el-tooltip>
                <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
              </el-button-group>
              <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems" :key="item.field"
                  v-model="item.off" :label="item.label" border>
                </el-checkbox>
              </div>

            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx';
import Sortable from 'sortablejs';
import {
  findCusTypeCombo, serviceCenterfindComboCusList, getServiceMans, sumCusGathPay, adupPrivateSet, getPrivateSetList,

} from '@/api/login.js'
onMounted(() => {
  luser.value = JSON.parse(localStorage.getItem("luser"))
  timeTypeTime.value = [new_day1(), to_day1()]
  find_data.stime = new_day()
  find_data.etime = to_day()
  findCusTypeCombo({}).then(res => {
    findCusTypeCombo_list.value = res.data
  })
  serviceCenterfindComboCusList({
    page: {
      pageNum: 1,
      pageSize: 9999,
    },
  }).then(res => {
    serviceCenterfindComboCusList_list.value = res.data
    serviceCenterfindComboCusList_list2.value = res.data
  })
  getServiceMans({}).then(res => {
    getServiceMans_list.value = res.data
  })
  getPrivateSetList({
    find: '应收应支',
    page: {
      pageNum: 1,
      pageSize: 999,
    },
  }).then(res => {
    if (res.data.list[0]) {
      table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
    } else {
      table_data_list_new.value = table_data_list
    }
  })
  Sortable.create(sortableContainer.value, {
    draggable: '.drag_it',
    ghostClass: 'sortable-ghost',
    onEnd: evt => {
      const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
      table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

      // 重新赋值给列数组
      // let cols = that.U.scopy(that.fields);
      // let list = cols.filter(it => { return it.show; });
      // that.$emit('saveSet', {dgName: that.dgName, cols: list});
    }
  })
  list_api()
})

const luser = ref({})
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const timeTypeTime = ref([])
const timeTypeTime_btn = (e) => {
  if (e) {
    timeTypeTime.value = e
    find_data.stime = timeTypeTime.value[0] + ' ' + '00:00:00'
    find_data.etime = timeTypeTime.value[1] + ' ' + '23:59:59'
    find_data.timeType = '0'
  } else {
    timeTypeTime.value = ''
    find_data.stime = ''
    find_data.etime = ''
    find_data.timeType = ''
  }
}
const new_day = () => {
  // 获取当前日期
  let currentDate = new Date();

  // 计算上个月的年份和月份
  let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
  let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

  // 构建上个月的日期
  let firstDayOfLastMonth = new Date(year, month, 1);

  // 格式化为 yyyy-mm-dd
  let formattedDate = `${firstDayOfLastMonth.getFullYear()}-${(firstDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-01`;

  let formattedDate2 = `${formattedDate} 00:00:00`;
  return formattedDate2
}
const to_day = () => {
  // 获取当前日期
  let currentDate = new Date();

  // 计算上个月的年份和月份
  let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
  let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

  // 获取上个月的最后一天
  let lastDayOfLastMonth = new Date(year, month + 1, 0);

  // 格式化为 yyyy-mm-dd
  let formattedDate = `${lastDayOfLastMonth.getFullYear()}-${(lastDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-${lastDayOfLastMonth.getDate()}`;

  let formattedDate2 = `${formattedDate} 23:59:59`;
  return formattedDate2
}
const new_day1 = () => {
  // 获取当前日期
  let currentDate = new Date();

  // 计算上个月的年份和月份
  let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
  let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

  // 构建上个月的日期
  let firstDayOfLastMonth = new Date(year, month, 1);

  // 格式化为 yyyy-mm-dd
  let formattedDate = `${firstDayOfLastMonth.getFullYear()}-${(firstDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-01`;

  let formattedDate2 = `${formattedDate}`;
  return formattedDate2
}
const to_day1 = () => {
  // 获取当前日期
  let currentDate = new Date();

  // 计算上个月的年份和月份
  let year = currentDate.getMonth() === 0 ? currentDate.getFullYear() - 1 : currentDate.getFullYear();
  let month = currentDate.getMonth() === 0 ? 11 : currentDate.getMonth() - 1;

  // 获取上个月的最后一天
  let lastDayOfLastMonth = new Date(year, month + 1, 0);

  // 格式化为 yyyy-mm-dd
  let formattedDate = `${lastDayOfLastMonth.getFullYear()}-${(lastDayOfLastMonth.getMonth() + 1).toString().padStart(2, '0')}-${lastDayOfLastMonth.getDate()}`;

  let formattedDate2 = `${formattedDate}`;
  return formattedDate2
}
const findCusTypeCombo_list = ref([])
const serviceCenterfindComboCusList_list = ref([])
const serviceCenterfindComboCusList_list2 = ref([])
const handleFilter_change = (e) => {
  if (e) {
    for (let i = 0; i < serviceCenterfindComboCusList_list2.value.length; i++) {
      if (serviceCenterfindComboCusList_list2.value[i].userId == e) {
        find_data.id = serviceCenterfindComboCusList_list2.value[i].id
      }
    }
  } else {
    find_data.id = ''
    find_data.userId = ''
  }

}
const handleFilter = (value) => {
  // 自定义筛选逻辑
  if (value) {
    let results = serviceCenterfindComboCusList_list2.value.filter(item => {
      for (let key in item) {
        if (typeof item[key] === 'string' && item[key].includes(value)) {
          return true;
        }
      }
      return false;
    })
    if (results.length > 0) {
      serviceCenterfindComboCusList_list.value = results
    } else {
      serviceCenterfindComboCusList_list.value = []
    }
  } else {
    serviceCenterfindComboCusList_list.value = serviceCenterfindComboCusList_list2.value
  }
}
const getServiceMans_list = ref([])
const totalGath = ref(0)
const totalPay = ref(0)
const find_data = reactive({

  page: {
    pageNum: 1,
    pageSize: 20,
  },
  cusTypeId: '',
  etime: '',
  id: '',
  serviceMan: '',
  stime: '',
  userId: '',

})
const list_data = ref([])
const total = ref(0)
// 分页器一夜显示多少数据页面
const size_change_btn = () => {
  find_data.page.pageNum = 1
  list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
  list_api()
}
const list_api = () => {
  sumCusGathPay(find_data).then(res => {
    list_data.value = res.data.data
    // total.value = res.data.list.total
    totalGath.value = res.data.totalGath
    totalPay.value = res.data.totalPay
  })
}
//#region 表格数据处理
const table_data_list = reactive([
  { label: '客户单位名称', field: 'companyName', width: 98, off: true },
  { label: '业务负责人', field: 'dutyName', width: 124, off: true },
  { label: '首次欠款时间', field: 'firstTime', width: 103, off: true },
  { label: '应收金额', field: 'gathMoney', width: 74, off: true },
  { label: '应付金额', field: 'payMoney', width: 73, off: true },
  { label: '余额', field: 'balance', width: 61, off: true },
  { label: '业务员', field: 'serviceName', width: 158, off: true },
  { label: '客户性质', field: 'cusType', width: 150, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
  icon_off.value = !icon_off.value
  console.log(sortableContainer.value)

}
const resetTableSet = () => {
  console.log(table_data_list)
  table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))

}
const saveTableSet = () => {
  adupPrivateSet({
    dat: JSON.stringify(table_data_list_new.value),
    tbName: '应收应支',
    tbNum: "sumCusGathPay",
  }).then(res => {
    if (res.code == 1) {
      return ElMessage({
        message: res.msg,
        type: 'success',
      })
    } else {
      return ElMessage({
        message: res.msg,
        type: 'warning',
      })
    }
  })
  icon_off.value = false
}
const headerdragend = (newWidth, oldWidth, column) => {
  console.log(newWidth, oldWidth, column)
  for (let i = 0; i < table_data_list_new.value.length; i++) {
    if (column.property == table_data_list_new.value[i].field) {
      table_data_list_new.value[i].width = newWidth
    }
  }
}
const checkbox_btn = (e, c) => {
  for (let i = 0; i < table_data_list_new.value.length; i++) {
    if (table_data_list_new.value[i].label == c.target._value) {
      table_data_list_new.value[i].off == e

    }

  }

}

const sortedItems = computed(() => {
  return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion
const list_page = ref({
  pageNum: 1,
  pageSize: 100,
})
const ex_getWalletListForBack_btn = () => {
  let title = luser.value.companyName + '应收应支统计表.xlsx'
  let ps = {
    page: {
      pageNum: 1,
      pageSize: 20,
    },
    cusTypeId: find_data.cusTypeId,
    etime: find_data.etime,
    id: find_data.id,
    serviceMan: find_data.serviceMan,
    stime: find_data.stime,
    userId: find_data.userId,
  }

  sumCusGathPay(ps).then(res => {
    if (res.code == 1) {

      const data = [
        ['客户单位名称', '应收金额', '应付金额', '余额', '业务负责人', '业务员', '首次欠款时间', '客户性质',],
      ];
      for (let i = 0; i < res.data.data.length; i++) {
        let ps = {
          companyName: res.data.data[i].companyName,
          gathMoney: res.data.data[i].gathMoney,
          payMoney: res.data.data[i].payMoney,
          balance: res.data.data[i].balance,
          dutyName: res.data.data[i].dutyName,
          serviceName: res.data.data[i].serviceName ? res.data.data[i].serviceName.split('-')[1] + '-' +
            res.data.data[i].serviceName.split('-')[2] : '',
          firstTime: res.data.data[i].firstTime,
          cusType: res.data.data[i].cusType,


        }
        data.push(Object.values(ps))
      }

      const ws = XLSX.utils.aoa_to_sheet(data);
      ws['!cols'] = [{ width: 30 }, { width: 10 }, { width: 10 }, { width: 10 }, { width: 25 }, { width: 25 }, { width: 30 }, { width: 15 }];
      const wb = XLSX.utils.book_new();


      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      XLSX.writeFile(wb, title);

      return ElMessage({
        message: res.msg,
        type: 'success',
      })
    } else {
      return ElMessage({
        message: res.msg,
        type: 'warning',
      })
    }

  })
}
</script>

<style scoped lang='less'>
.time-wrapper {
  display: flex;
  justify-content: space-between;
  padding-bottom: 10px;

  .bigTitle {
    display: inline-block;
    border-bottom: none;
    padding: 8px 0;
    color: #3A71A8;
    margin-right: 20px;
    font-size: 18px;
    font-weight: bold;
    white-space: nowrap;
  }
}

::v-deep(.empty-car-list) {
  overflow: hidden;
  @borderColor: #1890ff;

  .car-list {
    display: inline-block;
    vertical-align: top;
    margin-left: 10px;

    .c-gray {
      display: block;
      text-align: center;
      font-size: 15px;
      padding: 20px 0 40px 0;
      color: #929292 !important;
    }

    .sort_wrapper {
      display: inline-block;
      vertical-align: top;
      width: 50px;
      text-align: center;
      border: 1px solid @borderColor;

      .sort_title {
        width: 50px;
        font-size: 12px;
        height: 20px;
        line-height: 20px;
        color: white;
        background: #393B6A;
      }

      .sort_empty {
        width: 50px;
        height: 21px;
        line-height: 20px;
        background: #ecebeb;
        border-bottom: 1px solid @borderColor;
      }

      .sort_item {
        width: 50px;
        height: 20px;
        line-height: 20px;
        font-size: 12px;
        border-bottom: 1px solid @borderColor;

        &:last-child {
          border-bottom: none;
        }
      }
    }
  }

  .toggleOpen {
    width: 20px;
    display: inline-block;
    vertical-align: top;
    text-align: center;
    line-height: 343px;
    height: 343px;
    background: #f5f5f5;
    margin-left: -1px;
    border: 1px solid @borderColor;

    &:hover {
      cursor: pointer;
      background: #e8e8e8;

      i {
        color: @borderColor;
      }
    }
  }

  .throw_wrapper {
    display: inline-block;
    vertical-align: top;
    margin-left: -1px;
    border: 1px solid @borderColor;
    border-top: none;
    box-sizing: border-box;

    .title {
      background: #393B6A;
      color: #fff;
      height: 21px;
      line-height: 20px;
      font-size: 12px;
      text-align: center;
    }

    .content_wrapper {
      display: flex;
      padding-top: 1px;

      .items {
        width: 70px;
        text-align: center;
        font-size: 12px;
        font-weight: normal;
        border-right: 1px solid #1890ff;
        overflow: hidden;

        &:last-child {
          border-right: none;
        }

        .smallTitle {
          height: 20px;
          line-height: 20px;
          background: #ecebeb;
          border-bottom: 1px solid #1890ff;
        }

        .error_item {
          height: 20px;
          line-height: 20px;
          box-sizing: border-box;
          border-bottom: 1px solid #1890ff;

          &:last-child {
            border-bottom: none;
          }
        }
      }
    }
  }

  .toggleMore {
    width: 100%;
    text-align: center;
    padding: 10px 0;
    font-size: 14px;
    border: 1px solid @borderColor;
    border-top: none;

    &:hover {
      cursor: pointer;
      color: @borderColor;
    }
  }

}
</style>
